#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include "../include/meta.h"
#include "../include/vfs_errorcodes.h"
char* unmount_vfs(char label[])
{	
//displayBstTree(bstroot);
//printf("displaying tree");
//	displayTree(root);
	char result[100];
	if(strcmp(label,"")==0)
	{
		strcpy(result,"unmountvfs_FAILURE ");
		strcat(result,ERR_VFS_UNMOUNT_00);
		sprintf(str, "%s",result);
		return str;
	}
	
	
	if(root==NULL)
	{
		strcpy(result,"unmountvfs_FAILURE ");
		strcat(result,ERR_VFS_UNMOUNT_03);
		sprintf(str, "%s",result);
		return str;	//VFS_NOT_MOUNTED
	}
	

	if(strcmp(main_header_var->label,label) !=0)
		{
			//printf("the label is %s,%s",main_header_var->label,label);
			strcpy(result,"unmountvfs_FAILURE ");
			strcat(result,ERR_VFS_UNMOUNT_02);
			sprintf(str, "%s",result);
			return str;
			//ACCESS_DENIED
		}
			strcat(label,".dat");
	FILE *fp_check, *fp;
	fp=fopen(mounted_vfs, "rb+");
	
	fp_check = fopen(label, "rb+");
	if(fp_check==0)
	{
		fclose(fp_check);
		strcpy(result,"unmountvfs_FAILURE ");
		strcat(result,ERR_VFS_UNMOUNT_01);
		sprintf(str, "%s",result);
		return str;
		 //DATA_FILE_NOT_FOUND
	}
	
	else
	{
	fclose(fp_check);	
	int x;
	x=ftell(fp);
	//printf("%d - b4",x);
	rewind(fp);
	x=ftell(fp);
	//printf("%d - after ",x);
	fwrite(main_header_var,sizeof(main_header),1,fp);
	x=ftell(fp);
	//printf("the mh is %d",x);
		///if(fl[0].a == 1)
	/*int i=0;
			while(i<size)
	{
		if(fl[i].a == 1)
		{
		//printf("%d",i);
		//printf("%s",fd[i].location_path);		
		
		}
	i++;
	}*/
	
	//printf("size is %d",size);
	fwrite(fd,size*sizeof(file_descriptor),1,fp);	
	x=ftell(fp);
	//printf("the fd is %d",x);
	fwrite(fl,size*sizeof(freelist),1,fp);
x=ftell(fp);
	//printf("the fl %d",x);
	fwrite(bl,bl_size*sizeof(blocklist),1,fp);
	x=ftell(fp);
	//printf("the main_header_size is %d",x);
	
	free(fd);
	free(fl);
	fclose(fp);
	free(bl);
	free(main_header_var);
	//free_nary(root);
	free(root->lchild);
	//free(root);
	root=NULL;
	
	//free(hash_table);
    free_bst(bstroot);
    bstroot=NULL;
	
	return "unmountvfs_SUCCESS";
}
}
